package com.heima.user.service.impl;

import cn.hutool.core.lang.UUID;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.constants.ApUserConstants;
import com.heima.feign.wemedia.WemediaFeignClient;
import com.heima.file.MinIOTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.entity.ApUser;
import com.heima.model.user.entity.ApUserRealname;
import com.heima.model.wemedia.entity.WmUser;
import com.heima.user.dao.ApUserDao;
import com.heima.user.dao.ApUserRealnameDao;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.utils.AppThreadLocalUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * APP实名认证信息表(ApUserRealname)表服务实现类
 *
 * @author makejava
 * @since 2022-04-23 17:55:02
 */
@Service("apUserRealnameService")
public class ApUserRealnameServiceImpl implements ApUserRealnameService {
    @Resource
    private ApUserRealnameDao apUserRealnameDao;

    @Resource
    private MinIOTemplate minIOTemplate;

    @Resource
    private ApUserDao apUserDao;

    @Resource
    private WemediaFeignClient wemediaFeignClient;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ApUserRealname queryById(Long id) {
        return this.apUserRealnameDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param apUserRealname 实例对象
     * @return 实例对象
     */
    @Override
    public ApUserRealname insert(ApUserRealname apUserRealname) {
        this.apUserRealnameDao.insert(apUserRealname);
        return apUserRealname;
    }

    /**
     * 修改数据
     *
     * @param apUserRealname 实例对象
     * @return 实例对象
     */
    @Override
    public ApUserRealname update(ApUserRealname apUserRealname) {
        this.apUserRealnameDao.update(apUserRealname);
        return this.queryById(apUserRealname.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.apUserRealnameDao.deleteById(id) > 0;
    }

    /**
     * 用户实名认证
     *
     * @param font_image
     * @param back_image
     * @param hold_image
     * @param live_image
     * @param name
     * @param idno
     * @return
     */
    @Override
    public ResponseResult submit(MultipartFile font_image, MultipartFile back_image, MultipartFile hold_image, MultipartFile live_image, String name, String idno) {
        //1.参数校验
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(idno)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setName(name);
        apUserRealname.setIdno(idno);
        apUserRealname.setUserId(AppThreadLocalUtil.getId());
        apUserRealname.setStatus(1);
        apUserRealname.setCreatedTime(new Date());
        apUserRealname.setUpdatedTime(new Date());

        try {
            //2.图片上传到minio
            if (!font_image.isEmpty()) {
                String originalFilename = font_image.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + suffix;
                String font_image_url = minIOTemplate.uploadImgFile("", fileName, font_image.getInputStream());
                apUserRealname.setFontImage(font_image_url);
            }

            if (!back_image.isEmpty()) {
                String originalFilename = back_image.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + suffix;
                String back_image_url = minIOTemplate.uploadImgFile("", fileName, back_image.getInputStream());
                apUserRealname.setBackImage(back_image_url);
            }

            if (!hold_image.isEmpty()) {
                String originalFilename = hold_image.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + suffix;
                String hold_image_url = minIOTemplate.uploadImgFile("", fileName, hold_image.getInputStream());
                apUserRealname.setHoldImage(hold_image_url);
            }

            if (!live_image.isEmpty()) {
                String originalFilename = live_image.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + suffix;
                String live_image_url = minIOTemplate.uploadImgFile("", fileName, live_image.getInputStream());
                apUserRealname.setLiveImage(live_image_url);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVICE_BUSY);
        }

        //3.封装数据保存
        apUserRealnameDao.insert(apUserRealname);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 实名认证列表展示
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.开启分页查询
        PageHelper.startPage(dto.getPage(), dto.getSize());
        Page<ApUserRealname> page = apUserRealnameDao.queryByStatus(dto.getStatus());
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getResult());
        return responseResult;

    }

    /**
     * 自媒体用户审核
     *
     * @param dto
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult updateStatus(AuthDto dto, Integer status) {
        //1.参数校验
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.如果审核失败，修改用户状态
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        //根据传进来的status来修改
        apUserRealnameDao.update(apUserRealname);
        //3.如果审核成功，需要创建自媒体账号，通过Feign远程调用
        if (status.equals(ApUserConstants.PASS_AUTH)) {
            createWmUser(dto);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建自媒体账号
     * @param dto
     */
    private void createWmUser(AuthDto dto) {
        //1.参数校验
        Long userRealnameId = dto.getId();
        //查询用户认证信息
        ApUserRealname apUserRealname = apUserRealnameDao.queryById(userRealnameId);
        if (apUserRealname == null || apUserRealname.getUserId() == null) {
            throw new RuntimeException("实名认证信息不存在");
        }

        //查询APP段用户信息
        ApUser apUser = apUserDao.queryById(apUserRealname.getUserId());
        if (apUser == null) {
            throw new RuntimeException("实名认证用户不存在");
        }

        //封装参数，创建自媒体账户
        WmUser wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setStatus(1);
        wmUser.setType(0);
        wmUser.setAvator(apUser.getImage());
        wmUser.setCreateTime(new Date());
        wmUser.setUpdateTime(new Date());
        wemediaFeignClient.save(wmUser);
    }
}
